package com.chris.homecare.screens
{
	import com.chris.homecare.components.HeaderComponent;
	import com.chris.homecare.data.DataUtil;
	import com.chris.homecare.data.FetchRemoteData;
	import com.chris.homecare.utils.CommonUtils;
	import com.chris.homecare.utils.ShowNativeAlert;
	
	import flash.events.Event;
	import flash.events.GeolocationEvent;
	import flash.events.IOErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.sensors.Geolocation;
	
	import feathers.WebView;
	import feathers.controls.Button;
	import feathers.controls.Label;
	import feathers.controls.LayoutGroup;
	import feathers.controls.Screen;
	import feathers.layout.HorizontalLayout;
	import feathers.layout.VerticalLayout;
	
	import starling.events.Event;
	
	[Event(name="triggerChangePatient", type="starling.events.Event")]
	public class LocationScreen extends Screen
	{
		public static const TRIGGER_CHANGE_PATIENT:String = "triggerChangePatient";
		
		private var webView:WebView;
		private var header:HeaderComponent;
		
		private var geo:Geolocation;
		private var webViewLoaded:Boolean = false;
		private var patientComp:LayoutGroup;

		private var latitude:String = "";
		private var longitude:String = "";
		
		public function LocationScreen()
		{
			super();
		}
		
		override protected function draw():void
		{
			webView.width = stage.stageWidth;
			webView.height = stage.stageHeight - header.height - patientComp.height - 20;
			super.draw();
		}
		
		override protected function initialize():void
		{
			FetchRemoteData.getClient().getPatientList(DataUtil.getUserEmail());
			
			this.layout = new VerticalLayout();
			
			header = new HeaderComponent();
			header.addEventListener(starling.events.Event.COMPLETE, onMenuBtnTrigger);
			addChild(header);
			
			webView = new WebView();
			webView.loadURL("http://speiusscare.co.uk/maps.html");
			webView.addEventListener(WebView.EVENT_COMPLETE, onWebViewLoadComplete);
			addChild(webView);
			
			patientComp = new LayoutGroup();
			var patientCompLayout:HorizontalLayout = new HorizontalLayout();
			patientCompLayout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE;
			patientCompLayout.gap = 20;
			patientCompLayout.paddingTop = patientCompLayout.paddingLeft = 10;
			patientComp.layout = patientCompLayout;
			addChild(patientComp);
			var patientLabel:Label = new Label();
			patientLabel.text = "Choose Patient: ";
			patientLabel.nameList.add("form-heading-lbl");
			patientComp.addChild(patientLabel);
			
			var patientBtn:Button = new Button();
			patientBtn.label = FetchRemoteData.choosenPatient.header;
			
			if(FetchRemoteData.choosenPatient.address != "")
			{
				getGeoCode(FetchRemoteData.choosenPatient.address);
			}
			patientBtn.addEventListener(starling.events.Event.TRIGGERED, onPatientBtnTriggered);
			patientBtn.width = 240*CommonUtils.scaleValue;
			patientBtn.nameList.add("plain-btn");
			patientComp.addChild(patientBtn);
			
			var locationBtn:Button = new Button();
			locationBtn.nameList.add("location-notify-btn");
			locationBtn.addEventListener(starling.events.Event.TRIGGERED, submitGeoCodeLocation);
			locationBtn.width = locationBtn.height = 80*CommonUtils.scaleValue;
			patientComp.addChild(locationBtn);
			
			patientComp.includeInLayout = false;
			patientComp.visible = false;
			if(CommonUtils.patientListCollection && CommonUtils.patientListCollection.length > 0)
			{
				patientComp.includeInLayout = true;
				patientComp.visible = true;
			}
			
			super.initialize();
			
			if (Geolocation.isSupported) 
			{ 
				geo = new Geolocation();
				if (!geo.muted) 
				{
					geo.addEventListener(GeolocationEvent.UPDATE, geoUpdateHandler); 
				}
				else
				{
					trace("Please turn on Geolocation services");
				}
				geo.addEventListener(StatusEvent.STATUS, geoStatusHandler);
			} 
			else 
			{ 
				trace("Geolocation not supported"); 
			} 
		}
		
		private function onPickerClicked():void
		{
			webView.visible = false;
		}
		
		public function geoStatusHandler(event:StatusEvent):void 
		{ 
			if (geo.muted)
				geo.removeEventListener(GeolocationEvent.UPDATE, geoUpdateHandler);
			else
				geo.addEventListener(GeolocationEvent.UPDATE, geoStatusHandler);
		}
		
		public function geoUpdateHandler(event:GeolocationEvent):void 
		{
			if(webViewLoaded)
			{
				webView.callJs("addNurseLocation", event.latitude.toString(),event.longitude.toString());
			}
		} 
		
		private function onWebViewLoadComplete(event:starling.events.Event):void
		{
			webViewLoaded = true;
		}
		
		private function onPatientBtnTriggered():void
		{
			this.dispatchEventWith(TRIGGER_CHANGE_PATIENT);
		}
		
		override public function dispose():void
		{
			webViewLoaded = false;
			super.dispose();
		}
		
		private function onMenuBtnTrigger(event:starling.events.Event):void
		{
			this.dispatchEventWith(starling.events.Event.COMPLETE, false, {page: "Menu"});
		}
		
		protected function getGeoCode(address:String):void
		{
			var request:URLRequest=new URLRequest();
			request.url="https://maps.googleapis.com/maps/api/geocode/json?address=" +address+ "&key=AIzaSyAjTT-SyzqrTw3wHrip7moIxUBUEt0yMa0";
			request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
			request.method = URLRequestMethod.GET;
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(flash.events.Event.COMPLETE, onGeoCodeDataReceived);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.load(request);
		}
		
		protected function submitGeoCodeLocation(address:String):void
		{
			var request:URLRequest=new URLRequest();
			request.url="http://speiusscare.co.uk/sitterApp/api.php?mod=users&method=doGoogleRouteRequest&staff_email="+DataUtil.getUserEmail()+"&lang_id="+longitude+"&lati_id="+latitude;
			request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
			request.method = URLRequestMethod.GET;
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(flash.events.Event.COMPLETE, onGeoCodeSubmitHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.load(request);
		}
		
		protected function onGeoCodeSubmitHandler(event:flash.events.Event):void
		{
			var alertObject:Object;
			alertObject = new Object();
			alertObject.message = "Your Location has been submitted.";
			alertObject.title = "Speiuss";
			alertObject.buttons = Vector.<String>(["OK"]);
			ShowNativeAlert.showAlert(alertObject);
		}
		
		protected function onGeoCodeDataReceived(event:flash.events.Event):void
		{
			var jsonArray:Object = JSON.parse(event.target.data);
			
			latitude = jsonArray.results[0].geometry.location.lat;
			longitude = jsonArray.results[0].geometry.location.lng;
			
			if(webViewLoaded)
			{
				webView.callJs("addPatientLocation", latitude,longitude);
			}
		}
		
		protected function onError(event:flash.events.Event):void
		{
			trace("GeocodeError"+event);
		}
	}
}